package org.jeecg.modules.xl.shengfutong.util;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.stream.Collectors;

/**
 * @author deco
 * @create 2025-03-10
 */
public class ShengFuTongSignUtil {
    // 签名函数，仅作为示例
    public static String sign(Map<String, Object> params, String privateKey) throws Exception {
        // 检查并转换私钥格式
        if (privateKey.startsWith("-----")) {
            privateKey = privateKey.replace("-----BEGIN RSA PRIVATE KEY-----", "").replace("-----END RSA PRIVATE KEY-----", "").replaceAll("\r?\n", "");
        }

        // 过滤掉值为空的参数
        Map<String, Object> filteredParams = params.entrySet().stream()
                .filter(e -> e.getValue() != null && !"".equals(e.getValue()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

        // 对参数进行排序并连接成一个字符串
        List<String> paramList = new TreeSet<>(filteredParams.keySet()).stream()
                .map(key -> String.format("%s=%s", key, filteredParams.get(key).toString()))
                .collect(Collectors.toList());
        String content = String.join("&", paramList);

        // 获取私钥对象
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PKCS8EncodedKeySpec keySpecPKCS8 = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey));
        PrivateKey priKey = kf.generatePrivate(keySpecPKCS8);

        // 对连接的字符串进行签名
        Signature sign = Signature.getInstance("SHA1WithRSA");
        sign.initSign(priKey);
        sign.update(content.getBytes("utf-8"));
        return Base64.getEncoder().encodeToString(sign.sign());
    }
    public static String verify(Map<String, Object> params, String privateKey) throws Exception {
        // 检查并转换私钥格式
        if (privateKey.startsWith("-----")) {
            privateKey = privateKey.replace("-----BEGIN RSA PRIVATE KEY-----", "").replace("-----END RSA PRIVATE KEY-----", "").replaceAll("\r?\n", "");
        }
        //T除sign
        params.remove("sign");
        // 过滤掉值为空的参数
        Map<String, Object> filteredParams = params.entrySet().stream()
                .filter(e -> e.getValue() != null && !"".equals(e.getValue()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

        // 对参数进行排序并连接成一个字符串
        List<String> paramList = new TreeSet<>(filteredParams.keySet()).stream()
                .map(key -> String.format("%s=%s", key, filteredParams.get(key).toString()))
                .collect(Collectors.toList());
        String content = String.join("&", paramList);

        // 获取私钥对象
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PKCS8EncodedKeySpec keySpecPKCS8 = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey));
        PrivateKey priKey = kf.generatePrivate(keySpecPKCS8);

        // 对连接的字符串进行签名
        Signature sign = Signature.getInstance("SHA1WithRSA");
        sign.initSign(priKey);
        sign.update(content.getBytes("utf-8"));
        return Base64.getEncoder().encodeToString(sign.sign());
    }

}
